package com.xuhuan.demo.file;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * @Author huan.xu
 * @Date 2023/6/15 14:39
 * @Description java 调用cmd实现压缩
 * windows下命令：D:\7-Zip\7z.exe a -t7z C:\Users\Administrator\Desktop\filedir-local.7z C:\Users\Administrator\Desktop\filedir
 *
 * linux下命令：7z a -t7z /sinitek/filedir-local.7z /sinitek/filedir
 */
@Slf4j
public class SevenZCompressUtil3 {

    /**
     * 私有构造器
     */
    private SevenZCompressUtil3() {
    }

    /**
     * 生成.zip压缩文件
     *
     * @param filePath    需要压缩的文件路径
     * @param zipFileName 生成压缩文件的文件名（全路径）
     * @throws Exception
     */
    public static Process generateZipFile(String filePath, String zipFileName) throws Exception {
        //zipToolPath 是本地7-Zip软件的安装路径
        String zipToolPath = "D:\\7-Zip\\7z.exe";
        zipToolPath = zipToolPath.replaceAll(" ", "\" \"");//所有空格都替换成带有双引号的空格
        String command = "cmd /c start /B "+zipToolPath + " a -t7z " + zipFileName + " " + filePath;
        System.out.println(command);
//        File file = new File(filePath);
        return Runtime.getRuntime().exec(command);
        //执行成功后在ZipFileName路径下可以找到相应的压缩文件
    }


    public static void main(String[] args) throws Exception {
        //大文件
        String smallPath = "C:\\Users\\Administrator\\Desktop\\filedir";
        String smallOutPath = "C:\\Users\\Administrator\\Desktop\\filedir-local2.7z";
        log.info("开始压缩文件，198M");
        long smallStartTime = System.currentTimeMillis();
        Process process = generateZipFile(smallPath, smallOutPath);

        InputStream inputStream = process.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
        String tmp = null;
        while((tmp=br.readLine())!=null){
            System.out.println(tmp);
        }

        long smallEndTime = System.currentTimeMillis();
        log.info("压缩文件完成，时间[{}]秒", (smallEndTime - smallStartTime) / 1000);


    }

}
